from django.contrib.contenttypes.models import ContentType
from django.core.cache import cache
from django.db.models import Q

from apps.pbi.models import Check, Pbi_Common_Pdfs, BusinessOpportunity, Status_change, Progress_thisweek, Contract, \
    Contract_Common_Pdfs, Order
from apps.system.models import Region
from extensions import serializers
from extensions.common.base import *
from extensions.serializers import *
from extensions.exceptions import *
from apps.pbi.models import *
from apps.system.models import *
from tools.func import get_model_fullname
from datetime import timedelta
from django.utils import timezone

class CheckFlowSerializer(BaseSerializer):
    class RolesSerializer(BaseSerializer):
        class Meta:
            model = Role
            fields = ['id', 'name']
    check_flow_steps=RolesSerializer(
        source='steps', many=True, read_only=True, label='审批步骤')
    class Meta:
        model = CheckFlow
        fields = ['id', 'name','check_flow_steps']


class ClientSerializer(BaseSerializer):
    company_name = CharField(source='company.name',  read_only=True, label='公司')
    creator_name = CharField(source='creator.name',  read_only=True, label='创建者')
    updater_name = CharField(source='updater.name',  read_only=True, label='更新者')
    client_property_name = CharField(source='client_property.name',  read_only=True, label='客户属性')
    cooperation_methods_items = serializers.SerializerMethodField()
    industry_types_items = serializers.SerializerMethodField()
    region_items = serializers.SerializerMethodField()

    class ChecksSerializer(BaseSerializer):
        check_user_name = CharField(source='check_user.name', read_only=True, label='审核人')
        class Meta:
            model = Check
            fields = ['id', 'check_user','check_user_name','opinion','is_agree','create_time']

    checks = ChecksSerializer(many=True, read_only=True, label='审核记录')

    class Meta:
        model = Client
        fields = '__all__'

    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        validated_data['updater'] = self.context['request'].user
        validated_data['company'] = self.context['request'].user.company
        return super().create(validated_data)

    def update(self, instance, validated_data):
        validated_data['updater'] = self.context['request'].user
        return super().update(instance, validated_data)

    def get_cooperation_methods_items(self, obj):
        if not isinstance(obj.cooperation_methods, list):
            return None
        cooperation_methods_names = []
        for id in obj.cooperation_methods:
            name = cache.get(id)
            if name is None:
                try:
                    dict_item = Dict_item.objects.get(id=id)
                    name = dict_item.name
                    cache.set(id, name, 60 * 60 * 24 * 7)
                except Dict_item.DoesNotExist:
                    name = None
            cooperation_methods_names.append(name)
        return '/'.join(cooperation_methods_names)

    def get_industry_types_items(self, obj):
        if not isinstance(obj.industry_types, list):
            return None
        industry_types_names = []
        for id in obj.industry_types:
            name = cache.get(id)
            if name is None:
                try:
                    dict_item = Dict_item.objects.get(id=id)
                    name = dict_item.name
                    cache.set(id, name, 60 * 60 * 24 * 7)  # 缓存 7天
                except Dict_item.DoesNotExist:
                    name = None
            industry_types_names.append(name)

        return '/'.join(industry_types_names)

    def get_region_items(self, obj):
        if not isinstance(obj.region, list):
            return None
        region_names = []
        for id in obj.region:
            name = cache.get(id)
            if name is None:
                try:
                    region_item = Region.objects.get(id=id)
                    name = region_item.region_name
                    cache.set(id, name, 60 * 60 * 24 * 7)  # 缓存 7天
                except Region.DoesNotExist:
                    name = None
            region_names.append(name)

        return '/'.join(region_names)

    # def validate_number(self, value):
    #     # content_type = ContentType.objects.get_for_model(Client)
    #     # models.UserInfo._meta.model_name
    #     # print(get_model_fullname(self.Meta.model))
    #     self.validate_unique({'number': value}, message=f'编号[{value}]已存在')
    #     return value

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value


class SupplierManufactorSerializer(BaseSerializer):
    company_name = CharField(source='company.name', read_only=True, label='公司')
    creator_name = CharField(source='creator.name', read_only=True, label='创建者')
    updater_name = CharField(source='updater.name', read_only=True, label='更新者')
    product_specialty_items = serializers.SerializerMethodField()

    class ChecksSerializer(BaseSerializer):
        check_user_name = CharField(source='check_user.name', read_only=True, label='审核人')

        class Meta:
            model = Check
            fields = ['id', 'check_user', 'check_user_name', 'opinion', 'is_agree', 'create_time']

    checks = ChecksSerializer(many=True, read_only=True, label='审核记录')

    class Meta:
        model = SupplierManufactor
        fields = '__all__'

    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        validated_data['updater'] = self.context['request'].user
        validated_data['company'] = self.context['request'].user.company
        return super().create(validated_data)

    def update(self, instance, validated_data):
        validated_data['updater'] = self.context['request'].user
        return super().update(instance, validated_data)

    def get_product_specialty_items(self, obj):
        if not isinstance(obj.product_specialty, list):
            return None
        product_specialty_names = []
        for id in obj.product_specialty:
            name = cache.get(id)
            if name is None:
                try:
                    dict_item = Dict_item.objects.get(id=id)
                    name = dict_item.name
                    cache.set(id, name, 60 * 60 * 24 * 7)
                except Dict_item.DoesNotExist:
                    name = None
            product_specialty_names.append(name)
        return '/'.join(product_specialty_names)

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value


class Pbi_Common_PdfsSerializer(BaseSerializer):
    company_name = CharField(source='company.name', read_only=True, label='公司')
    creator_name = CharField(source='creator.name',  read_only=True, label='填报人')
    class Meta:
        model = Pbi_Common_Pdfs
        read_only_fields = ['id', 'company','company_name','name','type',
                            'creator','creator_name','create_time']
        fields = ['file', *read_only_fields]

    def create(self, validated_data):
        validated_data['name'] = validated_data['file'].name
        validated_data['company'] = self.user.company
        validated_data['type'] = self.request.data['type']
        validated_data['creator'] = self.user
        return super().create(validated_data)



class SupplierIntegratorSerializer(BaseSerializer):

    company_name = CharField(source='company.name',  read_only=True, label='公司')
    creator_name = CharField(source='creator.name',  read_only=True, label='创建者')
    updater_name = CharField(source='updater.name',  read_only=True, label='更新者')
    introduce_method_name = CharField(source='introduce_method.name',  read_only=True, label='引入方式')

    class Pbi_Common_PdfsSerializer(BaseSerializer):
        class Meta:
            model = Pbi_Common_Pdfs
            fields = "__all__"

    business_license_pdf_item = Pbi_Common_PdfsSerializer(source='business_license_pdf', read_only=True,
                                                           label='营业执照附件')
    business_qualification_pdf_item = Pbi_Common_PdfsSerializer(source='business_qualification_pdf', read_only=True,
                                                           label='营业资质附件')

    class ChecksSerializer(BaseSerializer):
        check_user_name = CharField(source='check_user.name', read_only=True, label='审核人')
        class Meta:
            model = Check
            fields = ['id', 'check_user','check_user_name','opinion','is_agree','create_time']

    checks = ChecksSerializer(many=True, read_only=True, label='审核记录')

    class Meta:
        model = SupplierIntegrator
        fields = '__all__'

    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        validated_data['updater'] = self.context['request'].user
        validated_data['company'] = self.context['request'].user.company
        return super().create(validated_data)

    def update(self, instance, validated_data):
        validated_data['updater'] = self.context['request'].user
        return super().update(instance, validated_data)

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value


class ManufactorProductSerializer(BaseSerializer):
    company_name = CharField(source='company.name', read_only=True, label='公司')
    supplier_manufactor_name = CharField(source='supplier_manufactor.name', read_only=True, label='公司')
    creator_name = CharField(source='creator.name', read_only=True, label='创建者')
    updater_name = CharField(source='updater.name', read_only=True, label='更新者')
    product_specialty_items = serializers.SerializerMethodField()


    class Meta:
        model = ManufactorProduct
        fields = '__all__'

    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        validated_data['updater'] = self.context['request'].user
        validated_data['company'] = self.context['request'].user.company
        return super().create(validated_data)

    def update(self, instance, validated_data):
        validated_data['updater'] = self.context['request'].user
        return super().update(instance, validated_data)

    def get_product_specialty_items(self, obj):
        if not isinstance(obj.product_specialty, list):
            return None
        product_specialty_names = []
        for id in obj.product_specialty:
            name = cache.get(id)
            if name is None:
                try:
                    dict_item = Dict_item.objects.get(id=id)
                    name = dict_item.name
                    cache.set(id, name, 60 * 60 * 24 * 7)
                except Dict_item.DoesNotExist:
                    name = None
            product_specialty_names.append(name)
        return '/'.join(product_specialty_names)

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value


class ClientImportExportSerializer(BaseSerializer):
    # company = IntegerField(label='所属公司')
    number = CharField(label='客户编号(必填唯一)')
    name = CharField(label='客户名称(必填唯一)')
    profile = CharField(required=False, label='客户简介')
    cooperation_attribute = JSONField(required=False, label='合作方式，格式：[1,2]')
    cooperation_types = JSONField(required=False, label='合作行业类型，格式：[1,2]')
    contact = CharField(required=False, label='联系人')
    phone = CharField(required=False, label='手机号')
    email = CharField(required=False, label='邮箱')
    evaluate = CharField(required=False, label='客户评价')
    address = CharField(required=False, label='地址')
    remark = CharField(required=False, label='备注')
    class Meta:
        model = Client
        fields = ['number', 'name', 'profile','cooperation_attribute',
                  'cooperation_types','contact', 'phone', 'email',
                  'evaluate','address', 'remark']


class SupplierManufactorImportSerializer(BaseSerializer):
    # company = IntegerField(label='所属公司')
    number = CharField(label='厂家编号(必填唯一)')
    name = CharField(label='厂家名称(必填唯一)')
    accounting_period = IntegerField(label='账期(月)')
    credit_limit = FloatField(label='信用额度(万元)')
    product_specialty = JSONField(required=False, label='产品覆盖专业，格式：[1,2]')
    contact = CharField(required=False, label='联系人')
    phone = CharField(required=False, label='手机号')
    email = CharField(required=False, label='邮箱')
    remark = CharField(required=False, label='备注')
    class Meta:
        model = SupplierManufactor
        fields = ['number', 'name', 'accounting_period','credit_limit',
                  'product_specialty','contact', 'phone', 'email',
                   'remark']


class SupplierIntegratorImportSerializer(BaseSerializer):
    number = CharField(label='集成商编号(必填唯一)')
    name = CharField(label='集成商名称(必填唯一)')
    business_scope = CharField(required=False, label='营业范围')
    business_qualification = CharField(required=False,label='营业资质')
    contact = CharField(required=False, label='联系人')
    phone = CharField(required=False, label='手机号')
    email = CharField(required=False, label='邮箱')
    remark = CharField(required=False, label='备注')
    class Meta:
        model = SupplierIntegrator
        fields = ['number', 'name', 'business_scope','business_qualification',
                  'contact', 'phone', 'email', 'remark']


class ManufactorProductImportSerializer(BaseSerializer):
    number = CharField(label='产品编号(必填唯一)')
    name = CharField(label='产品名称')
    product_model = CharField(required=False, label='产品型号')
    product_price = FloatField(required=False,label='产品单价')
    product_specialty = JSONField(required=False, label='产品覆盖专业，格式：[1,2]')
    supplier_manufactor = IntegerField(label='厂家id')
    class Meta:
        model = SupplierIntegrator
        fields = ['number', 'name', 'product_model','product_price',
                  'product_specialty', 'supplier_manufactor']


class ClientExportSerializer(BaseSerializer):

    # class Cooperation_typesSerializer(BaseSerializer):
    #
    #     class Meta:
    #         model = Cooperation_types
    #         fields = ['id', 'name']

    # cooperation_types_list = Cooperation_typesSerializer(
    #     source='cooperation_types.name', many=True, read_only=True, label='合作属性')
    # cooperation_types_list=Cooperation_typesSerializer(source='cooperation_types', read_only=True, label='合作属性')

    # print(cooperation_types_list)
    company_name = CharField(source='company.name', read_only=True, label='公司')

    # company = IntegerField(label='所属公司')
    number = CharField(label='客户编号')
    name = CharField(label='客户名称')
    profile = CharField(required=False, label='客户简介')
    # cooperation_attribute = JSONField(required=False, label='合作方式，格式：[1,2]')
    # cooperation_types = JSONField(required=False, label='合作行业类型，格式：[1,2]')
    contact = CharField(required=False, label='联系人')
    phone = CharField(required=False, label='手机号')
    email = CharField(required=False, label='邮箱')
    address = CharField(required=False, label='地址')
    remark = CharField(required=False, label='备注')
    is_effective = IntegerField(required=False, label='状态(默认: 0，-1=待修改，0=待审核，1=已生效)')
    class Meta:
        model = Client
        fields = [
            'company_name',
            'number', 'name', 'profile',
                  # 'cooperation_attribute','cooperation_types',
                  # 'cooperation_types_list',
                  'contact', 'phone', 'email', 'address', 'remark',
                  'is_effective']


class BusinessOpportunitySerializer(BaseSerializer):
    company_name = CharField(source='company.name', read_only=True, label='公司')
    creator_name = CharField(source='creator.name', read_only=True, label='创建者')
    updater_name = CharField(source='updater.name', read_only=True, label='更新者')
    client_name = CharField(source='client.name', read_only=True, label='甲方单位')
    business_type_name = CharField(source='business_type.name', read_only=True, label='甲方单位')
    industry_type_name = CharField(source='industry_type.name', read_only=True, label='甲方单位')
    project_properties_name = CharField(source='project_properties.name', read_only=True, label='甲方单位')
    project_source_name = CharField(source='project_source.name', read_only=True, label='甲方单位')
    project_status_name = CharField(source='project_status.name', read_only=True, label='甲方单位')
    business_opportunity_stage_name = CharField(source='business_opportunity_stage.name', read_only=True, label='甲方单位')
    project_expansion_stage_name = CharField(source='project_expansion_stage.name', read_only=True, label='甲方单位')
    traction_unit_name = serializers.CharField(source='traction_unit.name', read_only=True)
    traction_unit_contact = serializers.CharField(source='traction_unit.contact', read_only=True)
    traction_unit_phone = serializers.CharField(source='traction_unit.phone', read_only=True)
    development_responsible_person_name = serializers.CharField(source='development_responsible_person.name', read_only=True)
    development_responsible_person_phone = serializers.CharField(source='development_responsible_person.phone', read_only=True)
    support_responsible_person_name = serializers.CharField(source='support_responsible_person.name', read_only=True)
    support_responsible_person_phone = serializers.CharField(source='support_responsible_person.phone', read_only=True)
    dict_item_names = SerializerMethodField()
    updated_this_week = serializers.SerializerMethodField()
    days_since_update = serializers.SerializerMethodField()


    class ChecksSerializer(BaseSerializer):
        check_user_name = CharField(source='check_user.name', read_only=True, label='审核人')

        class Meta:
            model = Check
            fields = ['id', 'check_user', 'check_user_name', 'opinion', 'is_agree', 'create_time']

    checks = ChecksSerializer(many=True, read_only=True, label='审核记录')


    class Status_changesSerializer(BaseSerializer):
        creator_name = CharField(source='creator.name', read_only=True, label='创建者')
        project_status_name = CharField(source='project_status.name', read_only=True, label='项目状态')

        class Meta:
            model = Status_change
            fields = '__all__'

    status_changes = Status_changesSerializer(source='Status_changes_business_opportunity',many=True, read_only=True, label='审状态变化记录')

    class Progress_thisweeksSerializer(BaseSerializer):
        creator_name = CharField(source='creator.name', read_only=True, label='创建者')

        class Meta:
            model = Progress_thisweek
            fields = '__all__'

    progress_thisweeks = Progress_thisweeksSerializer(source='Progress_thisweek_business_opportunity',many=True, read_only=True, label='审状态变化记录')

    class Meta:
        model = BusinessOpportunity
        fields = '__all__'

    def is_updated_this_week(self, update_time):
        now = timezone.now()
        start_of_week = now - timedelta(days=now.weekday())
        end_of_week = start_of_week + timedelta(days=6)
        return start_of_week <= update_time <= end_of_week

    def get_updated_this_week(self, obj):
        return self.is_updated_this_week(obj.update_time)

    def days_since_last_update(self, update_time):
        now = timezone.now().date()
        update_date = update_time.date()
        days_difference = (now - update_date).days
        return days_difference

    def get_days_since_update(self, obj):
        return self.days_since_last_update(obj.update_time)

    def get_dict_item_names(self, obj):
        names = {
            'business_type_name': obj.business_type.name if obj.business_type else None,
            'industry_type_name': obj.industry_type.name if obj.industry_type else None,
            'project_properties_name': obj.project_properties.name if obj.project_properties else None,
            'project_source_name': obj.project_source.name if obj.project_source else None,
            'project_status_name': obj.project_status.name if obj.project_status else None,
            'business_opportunity_stage_name': obj.business_opportunity_stage.name if obj.business_opportunity_stage else None,
            'project_expansion_stage_name': obj.project_expansion_stage.name if obj.project_expansion_stage else None,
        }
        return names



    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        validated_data['updater'] = self.context['request'].user
        validated_data['company'] = self.context['request'].user.company
        return super().create(validated_data)

    def update(self, instance, validated_data):
        validated_data['updater'] = self.context['request'].user
        return super().update(instance, validated_data)

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        representation['is_frame_name'] = '是' if representation['is_frame'] else '否'
        representation['is_traction_name'] = '是' if representation['is_traction'] else '否'
        representation['updated_this_week_name'] = '是' if representation['updated_this_week'] else '否'
        # 添加状态描述
        status_mapping = {
            -1: '待修改',
            0: '待审核',
            1: '已生效'
        }
        representation['is_effective_name'] = status_mapping.get(representation['is_effective'], '未知状态')
        return representation


class OrderSerializer(BaseSerializer):
    company_name = CharField(source='company.name', read_only=True, label='公司')
    creator_name = CharField(source='creator.name', read_only=True, label='创建者')
    updater_name = CharField(source='updater.name', read_only=True, label='更新者')
    project_number = CharField(source='contract.business_opportunity.number', read_only=True, label='项目编号')
    project_name = CharField(source='contract.business_opportunity.name', read_only=True, label='项目名称')
    contract_number = CharField(source='contract.number', read_only=True, label='合同编号')
    contract_name = CharField(source='contract.name', read_only=True, label='合同名称')
    business_type_name = CharField(source='business_type.name', read_only=True, label='专业分类')
    order_signing_status_name = CharField(source='order_signing_status.name', read_only=True, label='订单签订状态')
    order_execution_status_name = CharField(source='order_execution_status.name', read_only=True, label='订单执行状态')


    class ChecksSerializer(BaseSerializer):
        check_user_name = CharField(source='check_user.name', read_only=True, label='审核人')

        class Meta:
            model = Check
            fields = ['id', 'check_user', 'check_user_name', 'opinion', 'is_agree', 'create_time']

    checks = ChecksSerializer(many=True, read_only=True, label='审核记录')


    class Meta:
        model = Order
        fields = '__all__'


    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        validated_data['updater'] = self.context['request'].user
        validated_data['company'] = self.context['request'].user.company
        return super().create(validated_data)

    def update(self, instance, validated_data):
        validated_data['updater'] = self.context['request'].user
        return super().update(instance, validated_data)

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value


    def to_representation(self, instance):
        representation = super().to_representation(instance)
        # 添加状态描述
        status_mapping = {
            -1: '待修改',
            0: '待审核',
            1: '已生效'
        }
        representation['is_effective_name'] = status_mapping.get(representation['is_effective'], '未知状态')
        return representation


class Contract_Common_PdfsSerializer(BaseSerializer):
    company_name = CharField(source='company.name', read_only=True, label='公司')
    creator_name = CharField(source='creator.name',  read_only=True, label='填报人')
    class Meta:
        model = Contract_Common_Pdfs
        read_only_fields = ['id', 'company','company_name','name','type',
                            'creator','creator_name','add_time']
        fields = ['file', *read_only_fields]

    def create(self, validated_data):
        validated_data['name'] = validated_data['file'].name
        validated_data['company'] = self.user.company
        validated_data['type'] = self.request.data['type']
        validated_data['creator'] = self.user
        return super().create(validated_data)


class ContractSerializer(BaseSerializer):
    company_name = CharField(source='company.name', read_only=True, label='公司')
    creator_name = CharField(source='creator.name', read_only=True, label='创建者')
    updater_name = CharField(source='updater.name', read_only=True, label='更新者')
    project_number = CharField(source='business_opportunity.number', read_only=True, label='项目编号')
    project_name = CharField(source='business_opportunity.name', read_only=True, label='项目名称')
    client_name = CharField(source='business_opportunity.client.name', read_only=True, label='甲方单位')
    budget = CharField(source='business_opportunity.budget', read_only=True, label='合同预算')
    is_frame = BooleanField(source='business_opportunity.is_frame', read_only=True, label='是否为框架合同')
    region_names = serializers.SerializerMethodField()  # 新增一个 region_names 字段

    class ChecksSerializer(BaseSerializer):
        check_user_name = CharField(source='check_user.name', read_only=True, label='审核人')

        class Meta:
            model = Check
            fields = ['id', 'check_user', 'check_user_name', 'opinion', 'is_agree', 'create_time']

    checks = ChecksSerializer(many=True, read_only=True, label='审核记录')

    class Contract_Common_PdfsSerializer(BaseSerializer):
        class Meta:
            model = Contract_Common_Pdfs
            fields = "__all__"

    contract_scan_pdf_item = Contract_Common_PdfsSerializer(source='contract_scan_pdf', read_only=True,
                                                           label='合同扫描件')
    project_review_form_item = Contract_Common_PdfsSerializer(source='project_review_form', read_only=True,
                                                           label='项目评审表')
    project_budget_form_item = Contract_Common_PdfsSerializer(source='project_budget_form', read_only=True,
                                                           label='项目预算表')
    financial_review_form_item = Contract_Common_PdfsSerializer(source='financial_review_form', read_only=True,
                                                           label='财务评审表')
    other_annex_item = Contract_Common_PdfsSerializer(source='other_annex', read_only=True,
                                                           label='其它附件')
    class Meta:
        model = Contract
        fields = '__all__'

    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        validated_data['updater'] = self.context['request'].user
        validated_data['company'] = self.context['request'].user.company
        return super().create(validated_data)

    def update(self, instance, validated_data):
        validated_data['updater'] = self.context['request'].user
        return super().update(instance, validated_data)

    def validate_name(self, value):
        self.validate_unique({'name': value}, message=f'名称[{value}]已存在')
        return value

    def get_region_names(self, obj):
        """返回 region 的 names"""
        # 注意，这里假设你的 region 是一个包含 Region id 的列表
        if obj.region:
            region_ids = obj.region
            region_names = []
            for region_id in region_ids:
                try:
                    region = Region.objects.get(id=region_id)
                    region_names.append(region.region_name)
                except Region.DoesNotExist:
                    continue
            return "/".join(region_names)
        return None

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        representation['is_frame_name'] = '是' if representation['is_frame'] else '否'
        # 添加状态描述
        status_mapping = {
            -1: '待修改',
            0: '待审核',
            1: '已生效'
        }
        representation['is_effective_name'] = status_mapping.get(representation['is_effective'], '未知状态')
        return representation


class BusinessOpportunitySigning_PredictionSerializer(BaseSerializer):
    company_name = CharField(source='company.name', read_only=True, label='公司')
    client_name = CharField(source='client.name', read_only=True, label='甲方单位')
    project_status_name = CharField(source='project_status.name', read_only=True, label='项目状态名称')
    signing_forecast_person_name = CharField(source='signing_forecast_person.name', read_only=True, label='签约预测者')


    class Meta:
        model = BusinessOpportunity
        fields = ['id','company_name','number', 'name',
                  'project_status',
                  'project_status_name',
                  'content',
                  'signing_forecast_person',
                  'signing_forecast_person_name',
                  'tax_rate', 'project_amount',
                  'budget', 'client_name',
                  'forecast_signing_time', 'forecast_time']

    def update(self, instance, validated_data):
        validated_data['signing_forecast_person'] = self.context['request'].user
        validated_data['forecast_time'] = timezone.now()
        return super().update(instance, validated_data)


__all__ = [
    'ClientSerializer',
    'SupplierManufactorSerializer',
    'ClientImportExportSerializer',
    'ClientExportSerializer',
    'CheckFlowSerializer',
    'SupplierManufactorImportSerializer',
    'SupplierIntegratorSerializer',
    'SupplierIntegratorImportSerializer',
    'ManufactorProductSerializer',
    'ManufactorProductImportSerializer',

]